
package com.shizhi.usp.serialport;

import android.os.AsyncTask;
import android.os.Handler;
import android.os.Message;
import android.serialport.SerialIoManager;
import android.serialport.hex.HexData;
import android.serialport.utils.SerialUtil;
import android.support.v4.os.AsyncTaskCompat;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;

import com.hjlys.serialportlib.CommonSerialport;
import com.shizhi.usp.base.BaseSerialFra;

import java.io.IOException;

/**
 * @author Created by Administrator on  2018-01-15
 * @version 1.0.
 */

public class SerialTestFraHJLY extends BaseSerialFra {

    CommonSerialport mSerialUtil;
    private static final String TAG = "SerialTestFra";

    static SerialTestFraHJLY mFra;

    public static SerialTestFraHJLY getInstance() {
        if (mFra == null) {
            mFra = new SerialTestFraHJLY();
        }
        return mFra;
    }

    @Override
    public boolean openSerial() {
        AsyncTaskCompat.executeParallel(new AsyncTask<Object, Object, String>() {
            @Override
            protected String doInBackground(Object... params) {
                String result = "請配置串口！！！";
                try {
                    closeSerial();
                    String[] port = getSerialPort();
                    if (port != null) {
                        mSerialUtil = new CommonSerialport(getContext(), port[0]);
                        mSerialUtil.open(port[0], Integer.valueOf(port[1]));

                        startReadThread();
                        result = "打开成功";
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    result = "打开失败:" + e.getMessage();
                }
                return result;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (!TextUtils.isEmpty(s)) {
                    Toast.makeText(mActivity, "" + s, Toast.LENGTH_SHORT).show();
                }
            }
        });
        return false;
    }

    private void startReadThread() {

        if (mReadThread == null)
            mReadThread = new ReadThread();
        mReadThread.start();

    }

    @Override
    public void closeSerial() {
        if (mSerialUtil != null) {
            mSerialUtil.close();
            mSerialUtil = null;
        }
    }


    @Override
    public void writeData(byte[] data) {
        if (mSerialUtil != null && data.length > 0) {
            try {
                mSerialUtil.write(data);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void writeData(byte[] data, int offset, int len) {

    }

    private ReadThread mReadThread;
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            receiverData(msg.obj.toString());
        }
    };

    class ReadThread extends Thread {
        @Override
        public void run() {
            super.run();
            while (mSerialUtil != null && !Thread.currentThread().isInterrupted()) {
                try {
                    Thread.sleep(100);
                    byte[] data = new byte[512];
                    int readLen = mSerialUtil.read(data);
                    if (readLen > 0) {
                        Message message = mHandler.obtainMessage();
                        if (isHex) {
                            byte[] newdata = new byte[readLen];
                            System.arraycopy(data, 0, newdata, 0, readLen);
                            message.obj = HexData.hexToString(newdata);
                        } else {
                            message.obj = new String(data, 0, readLen);
                        }
                        message.sendToTarget();
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

}
